package application

import (
	"github.com/rs/zerolog/log"
	"shyxy-model-agent/core/config"
	"shyxy-model-agent/pkg/model"
	"shyxy-model-agent/pkg/xsysinfo"
)

func New(opts ...config.AppOption) (*Application, error) {
	options := config.NewApplicationConfig(opts...)
	application := newApplication(options)
	caps, err := xsysinfo.CPUCapabilities()
	if err == nil {
		log.Debug().Msgf("CPU capabilities: %v", caps)
	}
	gpus, err := xsysinfo.GPUs()
	if err == nil {
		log.Debug().Msgf("GPU count: %d", len(gpus))
		for _, gpu := range gpus {
			log.Debug().Msgf("GPU: %s", gpu.String())
		}
	}

	//if options.UploadDir != "" {
	//	err := os.MkdirAll(options.UploadDir, 0750)
	//	if err != nil {
	//		return nil, fmt.Errorf("unable to create UploadDir: %q", err)
	//	}
	//}

	// turn off any process that was started by GRPC if the context is canceled
	go func() {
		<-options.Context.Done()
		log.Debug().Msgf("Context canceled, shutting down")
		err := application.ModelLoader().StopAllGRPC()
		if err != nil {
			log.Error().Err(err).Msg("error while stopping all grpc backends")
		}
	}()
	if options.WatchDog {
		wd := model.NewWatchDog(
			application.ModelLoader(),
			options.WatchDogBusyTimeout,
			options.WatchDogIdleTimeout,
			options.WatchDogBusy,
			options.WatchDogIdle)
		application.ModelLoader().SetWatchDog(wd)
		go wd.Run()
		go func() {
			<-options.Context.Done()
			log.Debug().Msgf("Context canceled, shutting down")
			wd.Shutdown()
		}()
	}
	log.Info().Msg("core/startup process completed!")
	if err := application.DBLoader().LoadMysqlConfig("db.json"); err != nil {
		log.Error().Err(err).Msg("startup.New:error while loading mysql config")
	}
	return application, nil
}
